/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.api.wlhy.etcfeeclouds;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.ApiEtcBaseReq;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.Deduction;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.InputinvoiceReq;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.Invoice;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.InvoiceList;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.OrderDataReq;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.TradeList;
import org.jeecg.modules.api.wlhy.etcfeeclouds.req.TradeListReq;
import org.jeecg.modules.third.digitalseal.utils.PdfEditUtil;
import org.jeecg.modules.third.etc.feeclouds.constant.enums.ChannelEnum;
import org.jeecg.modules.wlhy.etcfeeclouds.entity.HyEtcfeecloudsInputinvoice;
import org.jeecg.modules.wlhy.etcfeeclouds.entity.HyEtcfeecloudsInvoice;
import org.jeecg.modules.wlhy.etcfeeclouds.entity.HyEtcfeecloudsOrder;
import org.jeecg.modules.wlhy.etcfeeclouds.entity.HyEtcfeecloudsTrade;
import org.jeecg.modules.wlhy.etcfeeclouds.service.EtcFeeCloudService;
import org.jeecg.modules.wlhy.etcfeeclouds.service.IHyEtcfeecloudsInputinvoiceService;
import org.jeecg.modules.wlhy.etcfeeclouds.service.IHyEtcfeecloudsInvoiceService;
import org.jeecg.modules.wlhy.etcfeeclouds.service.IHyEtcfeecloudsOrderService;
import org.jeecg.modules.wlhy.etcfeeclouds.service.IHyEtcfeecloudsTradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 *  路耕ETC接收
 *
 * @author duanlikao
 * @created 2021/9/8
 */
@Api(tags="路耕ETC接收管理")
@RestController
@RequestMapping("/api/wlhy/etcfeeclouds")
@Slf4j
public class ApiEtcFeeCloudsController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiEtcFeeCloudsController.class);

    @Resource
    private EtcFeeCloudService etcFeeCloudService;

    @Resource
    private IHyEtcfeecloudsOrderService etcfeecloudsOrderService ;

    @Resource
    private IHyEtcfeecloudsTradeService etcfeecloudsTradeService;

    @Resource
    private IHyEtcfeecloudsInvoiceService etcfeecloudsInvoiceService;


    @Resource
    private  IHyEtcfeecloudsInputinvoiceService etcfeecloudsInputinvoiceService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @ApiOperation(value = "运单", httpMethod = "POST", response = Object.class, notes = "运单")
    @RequestMapping(value = "/order", method = { RequestMethod.HEAD, RequestMethod.POST })
    public Result <?> order(@ModelAttribute @Valid ApiEtcBaseReq apiEtcBaseReq ) {

        //校验
        etcFeeCloudService. check(ChannelEnum.ORDER , apiEtcBaseReq );
        //验证签名
        String sign =  etcFeeCloudService.getSign(apiEtcBaseReq);
        if(!sign.equals(apiEtcBaseReq.getSign()) ){
            return Result.error("验证签名失败！");
        }
        OrderDataReq orderData = JSONObject.parseObject(apiEtcBaseReq.getData(), OrderDataReq.class);
        if(orderData != null){
            HyEtcfeecloudsOrder etcfeecloudsOrder = OrderDataReqTOHyEtcfeecloudsOrder(orderData);

            QueryWrapper <HyEtcfeecloudsOrder> queryWrapper = new  QueryWrapper();
            queryWrapper.eq("order_num",orderData.getOrderNum());
            HyEtcfeecloudsOrder etcfeecloudsOrderDb =  etcfeecloudsOrderService.getOne(queryWrapper);
            if(etcfeecloudsOrderDb == null){
                etcfeecloudsOrderService.save(etcfeecloudsOrder);
            }else {
                etcfeecloudsOrder.setId(etcfeecloudsOrderDb.getId());
                etcfeecloudsOrderService.updateById(etcfeecloudsOrder);

            }
        }
        return Result.ok();
    }


    @ApiOperation(value = "交易", httpMethod = "POST", response = Object.class, notes = "交易")
    @RequestMapping(value = "/trade", method = { RequestMethod.HEAD, RequestMethod.POST })
    public Result <?> trade(@ModelAttribute @Valid ApiEtcBaseReq apiEtcBaseReq , HttpServletRequest req) {
        //校验
        etcFeeCloudService. check(ChannelEnum.TRADE , apiEtcBaseReq );
        //验证签名
        String sign =  etcFeeCloudService.getSign(apiEtcBaseReq);
        if(!sign.equals(apiEtcBaseReq.getSign()) ){
            return Result.error("验证签名失败！");
        }
        JSONObject jsonObject = JSONObject.parseObject(apiEtcBaseReq.getData());
        String orderNum = jsonObject.getString("orderNum");
        List <TradeListReq> tradeListReqs  = JSONObject.parseArray(jsonObject.getString("cardList"), TradeListReq.class);
        if(CollectionUtils.isNotEmpty(tradeListReqs)){
            for(TradeListReq tradeListReq : tradeListReqs){
                for(TradeList tradeList : tradeListReq.getTradeList()){
                    HyEtcfeecloudsTrade etcfeecloudsOrder = TradeTOEtcfeecloudsTrade(tradeList,orderNum);

                    QueryWrapper <HyEtcfeecloudsTrade> queryWrapper = new  QueryWrapper();
                    queryWrapper.eq("trade_id",tradeList.getTradeId());
                    HyEtcfeecloudsTrade etcfeecloudsTradeDb =  etcfeecloudsTradeService.getOne(queryWrapper);
                    if(etcfeecloudsTradeDb == null){
                        etcfeecloudsTradeService.save(etcfeecloudsOrder);
                    }else {
                        etcfeecloudsOrder.setId(etcfeecloudsTradeDb.getId());
                        etcfeecloudsTradeService.updateById(etcfeecloudsOrder);
                    }
                }
            }
        }
        return Result.ok();
    }

    @ApiOperation(value = "发票", httpMethod = "POST", response = Object.class, notes = "发票")
    @RequestMapping(value = "/invoice", method = { RequestMethod.HEAD, RequestMethod.POST })
    public Result <?> invoice(@ModelAttribute @Valid ApiEtcBaseReq apiEtcBaseReq , HttpServletRequest req) {
        //校验
        etcFeeCloudService. check(ChannelEnum.INVOICE , apiEtcBaseReq );
        //验证签名
        String sign =  etcFeeCloudService.getSign(apiEtcBaseReq);
        if(!sign.equals(apiEtcBaseReq.getSign()) ){
            return Result.error("验证签名失败！");
        }
        JSONObject jsonObject = JSONObject.parseObject(apiEtcBaseReq.getData());
        String orderNum = jsonObject.getString("orderNum");
        List <InvoiceList> invoiceLists = JSONObject.parseArray(jsonObject.getString("invoiceList"), InvoiceList.class);
         if(CollectionUtils.isNotEmpty(invoiceLists)){
            for(InvoiceList invoice : invoiceLists){
                HyEtcfeecloudsInvoice etcfeecloudsInvoice = InvoiceTOEtcfeecloudsInvoice(invoice, orderNum);
                QueryWrapper <HyEtcfeecloudsInvoice> queryWrapper = new QueryWrapper();
                queryWrapper.eq("trade_id", invoice.getTradeId());
                HyEtcfeecloudsInvoice etcfeecloudsInvoiceDb = etcfeecloudsInvoiceService.getOne(queryWrapper);
                if (etcfeecloudsInvoiceDb == null) {
                    etcfeecloudsInvoiceService.save(etcfeecloudsInvoice);
                } else {
                    etcfeecloudsInvoice.setId(etcfeecloudsInvoiceDb.getId());
                    etcfeecloudsInvoiceService.updateById(etcfeecloudsInvoice);
                }
            }
        }
        return Result.ok();
    }

    @ApiOperation(value = "进项发票", httpMethod = "POST", response = Object.class, notes = "进项发票")
    @RequestMapping(value = "/inputinvoice", method = { RequestMethod.HEAD, RequestMethod.POST })
    public Result <?> inputinvoice(@ModelAttribute @Valid ApiEtcBaseReq apiEtcBaseReq , HttpServletRequest req) {
        //校验
        etcFeeCloudService. check(ChannelEnum.INPUTINVOICE , apiEtcBaseReq );
        //验证签名
        String sign =  etcFeeCloudService.getSign(apiEtcBaseReq);
        if(!sign.equals(apiEtcBaseReq.getSign()) ){
            return Result.error("验证签名失败！");
        }
        List <InputinvoiceReq> inputinvoiceReqs = JSONObject.parseArray(apiEtcBaseReq.getData(), InputinvoiceReq.class);
        if(CollectionUtils.isNotEmpty(inputinvoiceReqs)){
            for(InputinvoiceReq inputinvoiceReq : inputinvoiceReqs){

                Deduction deduction = inputinvoiceReq.getDeduction();
                Invoice invoice = inputinvoiceReq.getInvoice();
                HyEtcfeecloudsInputinvoice etcfeecloudsInputinvoice = InputInvoiceTOEtcfeecloudsInvoice(deduction ,invoice);
                QueryWrapper <HyEtcfeecloudsInputinvoice> queryWrapper = new QueryWrapper();
                queryWrapper.eq("fphm", invoice.getFphm());
                HyEtcfeecloudsInputinvoice etcfeecloudsInputinvoiceDb = etcfeecloudsInputinvoiceService.getOne(queryWrapper);
                if (etcfeecloudsInputinvoiceDb == null) {
                    etcfeecloudsInputinvoiceService.save(etcfeecloudsInputinvoice);
                } else {
                    etcfeecloudsInputinvoice.setId(etcfeecloudsInputinvoiceDb.getId());
                    etcfeecloudsInputinvoiceService.updateById(etcfeecloudsInputinvoice);
                }
            }
        }

        return Result.ok();
    }




    public static HyEtcfeecloudsInputinvoice InputInvoiceTOEtcfeecloudsInvoice(Deduction deduction,Invoice invoice) {
        if (deduction == null || invoice == null) {
            return null;
        }
        HyEtcfeecloudsInputinvoice hyEtcfeecloudsInputinvoice = new HyEtcfeecloudsInputinvoice();

        hyEtcfeecloudsInputinvoice.setTaxno(invoice.getTaxno());
        hyEtcfeecloudsInputinvoice.setFphm(invoice.getFphm());
        hyEtcfeecloudsInputinvoice.setFpdm(invoice.getFpdm());
        hyEtcfeecloudsInputinvoice.setFpzt(Integer.valueOf(invoice.getFpzt()));
        hyEtcfeecloudsInputinvoice.setFpzl(invoice.getFpzl());
        hyEtcfeecloudsInputinvoice.setDeductionState( Integer.valueOf(deduction.getDeduction_state()) );
        hyEtcfeecloudsInputinvoice.setDeductionDate(deduction.getDeduction_date());
        return hyEtcfeecloudsInputinvoice;
    }


    public  HyEtcfeecloudsInvoice InvoiceTOEtcfeecloudsInvoice(InvoiceList invoice,String orderNum)  {
        if (invoice == null) {
            return null;
        }
        HyEtcfeecloudsInvoice hyEtcfeecloudsInvoice = new HyEtcfeecloudsInvoice();

        hyEtcfeecloudsInvoice.setOrderNum(orderNum);
        hyEtcfeecloudsInvoice.setSellerTaxpayerCode(invoice.getSellerTaxpayerCode());
        hyEtcfeecloudsInvoice.setAmount(new BigDecimal( invoice.getAmount()));
        hyEtcfeecloudsInvoice.setFee(new BigDecimal( invoice.getFee()));

        hyEtcfeecloudsInvoice.setFilePath(invoice.getFilePath());

        String nowDate =  DateUtils.dateToStringNoBar(new Date());
        String fileName = orderNum +"_"+invoice.getInvoiceNum()+".pdf";
        String dbpath =  PdfEditUtil.downLoadByUrl(invoice.getFilePath() ,uploadpath+"/feeclouds_invoice/"+nowDate,fileName);
        dbpath = StringUtils.isNotBlank(dbpath) ?  dbpath.replace(uploadpath, "") :StringUtils.EMPTY;

        hyEtcfeecloudsInvoice.setLocalPath(  dbpath );

        hyEtcfeecloudsInvoice.setInvoiceMakeTime(
                DateUtils.stringToDateTime(invoice.getInvoiceMakeTime())
        );
        hyEtcfeecloudsInvoice.setSellerName(invoice.getSellerName());
        hyEtcfeecloudsInvoice.setPlateNum(invoice.getPlateNum());
        hyEtcfeecloudsInvoice.setInvoiceNum(invoice.getInvoiceNum());
        hyEtcfeecloudsInvoice.setInvoiceCode(invoice.getInvoiceCode());
        hyEtcfeecloudsInvoice.setTotalAmount(new BigDecimal( invoice.getTotalAmount()));
        hyEtcfeecloudsInvoice.setTaxRate(new BigDecimal(invoice.getTaxRate()));
        hyEtcfeecloudsInvoice.setEnStationName(invoice.getEnStationName());
        hyEtcfeecloudsInvoice.setExStationName(invoice.getExStationName());
        hyEtcfeecloudsInvoice.setTradeFlowNo(invoice.getTradeFlowNo());

        hyEtcfeecloudsInvoice.setTotalTaxAmount(new BigDecimal( invoice.getTotalTaxAmount()));
        hyEtcfeecloudsInvoice.setExTime(
                DateUtils.stringToDateTime( invoice.getExTime())
        );
        hyEtcfeecloudsInvoice.setTradeId(invoice.getTradeId());
        hyEtcfeecloudsInvoice.setVehicleType(invoice.getVehicleType());
        hyEtcfeecloudsInvoice.setVehicleAxles(invoice.getVehicleAxles());

//        hyEtcfeecloudsInvoice.setTrafficStartTime(invoice.getTrafficStartTime());
//        hyEtcfeecloudsInvoice.setTrafficEndTime(invoice.getTrafficEndTime());
//        hyEtcfeecloudsInvoice.setProjectName(invoice.getProjectName());
        return hyEtcfeecloudsInvoice;
    }

    public static HyEtcfeecloudsTrade TradeTOEtcfeecloudsTrade(TradeList tradeList,String orderNum) {
        if (tradeList == null) {
            return null;
        }
        HyEtcfeecloudsTrade hyEtcfeecloudsTrade = new HyEtcfeecloudsTrade();
        hyEtcfeecloudsTrade.setOrderNum(orderNum);
        hyEtcfeecloudsTrade.setTradeFlowNo(tradeList.getTradeFlowNo());
        hyEtcfeecloudsTrade.setFee(
               new BigDecimal(tradeList.getFee())
        );
        hyEtcfeecloudsTrade.setState(Integer.valueOf(tradeList.getState()));
        hyEtcfeecloudsTrade.setExTime(
                DateUtils.stringToDateTime(tradeList.getExTime())
        );
        hyEtcfeecloudsTrade.setTradeId(tradeList.getTradeId());
        return hyEtcfeecloudsTrade;
    }

    private static HyEtcfeecloudsOrder OrderDataReqTOHyEtcfeecloudsOrder(OrderDataReq orderData) {
        if (orderData == null) {
            return null;
        }
        HyEtcfeecloudsOrder hyEtcfeecloudsOrder = new HyEtcfeecloudsOrder();
        hyEtcfeecloudsOrder.setState(Integer.valueOf(orderData.getState()));
        hyEtcfeecloudsOrder.setOrderNum(orderData.getOrderNum());
        hyEtcfeecloudsOrder.setCompanyName(orderData.getCompanyName());
        hyEtcfeecloudsOrder.setOwnCar(Integer.valueOf(orderData.getOwnCar()));
        hyEtcfeecloudsOrder.setTaxno(orderData.getTaxno());
        return hyEtcfeecloudsOrder;
    }


}